package com.ruoyi.database.config;

import com.ruoyi.database.config.DataSourceRouting;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {

    @Bean(name = "primary")
    public DataSource primaryDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://120.46.39.36:3306/merchant_cloud?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8");
        dataSource.setUsername("root");
        dataSource.setPassword("Huaweimima.1");
        return dataSource;
    }

    @Bean(name = "secondary")
    public DataSource secondaryDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://120.46.39.36:3306/company-cloud?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8");
        dataSource.setUsername("root");
        dataSource.setPassword("Huaweimima.1");
        return dataSource;
    }

    @Bean(name = "dataSource")
    public DataSourceRouting dataSourceRouting(
            @Qualifier("primary") DataSource primaryDataSource,
            @Qualifier("secondary") DataSource secondaryDataSource) {
        DataSourceRouting dataSourceRouting = new DataSourceRouting();

        // 设置默认数据源
        dataSourceRouting.setDefaultTargetDataSource(primaryDataSource);

        // 创建一个 Map 存储目标数据源
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("primary", primaryDataSource);
        targetDataSources.put("secondary", secondaryDataSource);

        // 设置目标数据源
        dataSourceRouting.setTargetDataSources(targetDataSources);
        return dataSourceRouting;
    }
}
